package compilers.node;

import java.io.BufferedWriter;
import java.util.Vector;

import org.antlr.runtime.Token;

import compilers.Node;
import compilers.output.ErrorOutput;
import compilers.table.MemScope;
import compilers.table.Scope;
import compilers.types.Type;

public class Identifier extends Node {
	private String fIdentifier;
	
	public Identifier(String fIdentifier) {
		super();
		this.setfIdentifier(fIdentifier);
	}
	
	public Identifier(String fIdentifier, Token token, Scope scope) {
		super();
		this.setfIdentifier(fIdentifier);
		this.replaceIdents(token, scope);
	}
	
	
	public String getString() {
		return getfIdentifier();
	}

	public void print(int tab) {
		for (int i=1;i<=tab;i++){System.out.print("\t");}System.out.print("|-");
		System.out.println("Identifier (" + getfIdentifier() + ")");
	}

	public void setfIdentifier(String fIdentifier) {
		this.fIdentifier = fIdentifier;
	}

	public void generate(BufferedWriter writer, MemScope scope) {
		// TODO Auto-generated method stub
		
	}

	public String getfIdentifier() {
		return fIdentifier;
	}
	
	public void replaceIdents(Token token, Scope scope) {
		char c[] = fIdentifier.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == '[') {
				int start = i;
				for (i = start; i < c.length; i++) {
					if (c[i] == ']') {
						
						String sub = fIdentifier.substring(start+1, i);
						
						try {
							Integer.parseInt(sub);
						} catch (Exception e) {
							Type tmp = scope.resolveVariable(sub, token);
							fIdentifier = fIdentifier.replaceAll(sub, Integer.toString((int)tmp.getfValue()));
						}
						
						if (start+1 == i) {
							new ErrorOutput(token, "No array size specified, dynamic arrays not supported.");
						}
						break;
					}
					if (i+1 == c.length) {
						new ErrorOutput(token, "In an identifier, [ cannot occur without ]");
					}
				}
			} else if (c[i] == ']') {
				new ErrorOutput(token, "In an identifier, ] cannot occur without [");
			}
		}
	}
	
	public Vector<Integer> getIndices(Token token) {
		Vector<Integer> indices = new Vector<Integer>();
		char c[] = fIdentifier.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == '[') {
				int start = i;
				for (i = start; i < c.length; i++) {
					if (c[i] == ']') {
						indices.add(Integer.parseInt(fIdentifier.substring(start+1, i)));
						if (start+1 == i) {
							new ErrorOutput(token, "No array size specified, dynamic arrays not supported.");
						}
						break;
					}
					if (i+1 == c.length) {
						new ErrorOutput(token, "In an identifier, [ cannot occur without ]");
					}
				}
			} else if (c[i] == ']') {
				new ErrorOutput(token, "In an identifier, ] cannot occur without [");
			}
		}
		return indices;
	}
}
